package com.ry.framework.shiro.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.ry.project.login.bean.Menu;
import com.ry.project.login.bean.ParamsData;
import com.ry.project.login.bean.Role;
import com.ry.project.login.bean.User;
import com.ry.project.login.service.IUserService;


public class MyRealm extends AuthorizingRealm{

	@Autowired
	private IUserService userService;
	
	// 验证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("------------------------------shiro 验证-------------------------------------");
		if(token.getPrincipal() == null) {
			return null;
		}
		String name = token.getPrincipal().toString();
		ParamsData pd=new ParamsData();
		pd.put("username", name);
		User user=userService.selectUserByUsername(pd);
		if(user == null) {
			return null;
		}else {
			//info对象表示realm登录对比信息，参数1:用户信息（真实登录中是登录user对象）；参数2：数据库中存的密码；参数3：盐；参数4：当前realm的名字
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(name, user.getPassword(), getName());
			return info;
		}
		
	}
	
	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		User user = (User) SecurityUtils.getSubject();
		System.out.println("------进行授权------");
		// 获取 登录用户名
		String name = (String) principals.getPrimaryPrincipal();
		// 查询 用户名称
		ParamsData pd=new ParamsData();
		pd.put("username", name);
		User user = userService.selectUserRoleByUsername(pd);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		for (Role role : user.getRoles()) {
			info.addRole(role.getRolename());
		}
		pd.put("userid", user.getId());
		List<Menu> menuList=userService.selectMenuByUsername(pd);
		
		for (Menu menu : menuList) {
			info.addStringPermission(menu.getPermission());
			System.out.print(menu.getPermission()+" ");
		}
		System.out.println("");
		
		return info;
	}
	
}
